package com.kun.framework.core.exception;

import com.kun.framework.core.compoment.AlertMessage;
import com.kun.framework.core.config.DefaultAbstractInitialize;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 全局异常处理
 *
 * @author gzc
 * @since 2024/7/31
 **/
public class GlobalExceptionHandler extends DefaultAbstractInitialize {
    private final static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 异常处理，捕获主线程的异常
     */
    @Override
    public void init() {
        // 捕捉未处理的异常
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            // 异常是否已处理
            AtomicBoolean isHandler = new AtomicBoolean(false);
            // 抛出栈信息
            if (e instanceof RuntimeException re) {
                handlerCustomerException(t, re, isHandler);
                if (re.getCause() instanceof InvocationTargetException ite) {
                    Throwable te = ite.getTargetException();
                    handlerCustomerException(t, te, isHandler);
                }
            }
            // 未处理的异常
            if (!isHandler.get()) {
                log.error("发生未知异常->", e);
                AlertMessage.error("发生未知异常", e);
            }

        });
    }

    /**
     * 处理自定义的异常
     *
     * @param t         线程
     * @param throwable 异常
     * @param isHandler 是否已经处理
     */
    private static void handlerCustomerException(Thread t, Throwable throwable, AtomicBoolean isHandler) {
        if (!isHandler.get()) {
            if (throwable instanceof BizException biz) {
                log.error(biz.getErrMsg(), biz);
                AlertMessage.error(biz.getErrMsg(), throwable);
                isHandler.set(true);
            } else if (throwable instanceof AbstractPopupException pe) {
                pe.getPopupMessageTypeEnum().getPopupCallback().accept(t, pe);
                isHandler.set(true);
            }
        }
    }
}
